(function(angular) {
  'use strict';
  var dependencies = ['oc.lazyLoad', 'ngResource', 'fs.router', 'fs.constant', 'fs.storage', 'fs.ajax', 'fs.date', 'fs.modal', 'fs.layout', 'fs.menu'];
  angular.module('fs.waf', dependencies).controller('mainController', mainController);
  /*.animation(".fade-in", [ "$animateCss", function($animateCss) {
		return {
			enter : function(element) {
				return $animateCss(element, {
					from : {
						opacity : 0
					},
					to : {
						opacity : 1
					},
					duration : 3
				});
			}
		};
	} ])
	.animation(".fade-out", [ "$animateCss", function($animateCss) {
		return {

			leave : function(element) {
				return $animateCss(element, {
					from : {
						opacity : 1
					},
					to : {
						opacity : 0
					},
					duration : 3
				});
			}
		};
	} ])*/

  mainController.$inject = [
    '$rootScope',
    '$scope',
    '$log',
    '$translate',
    '$locale',
    '$location',
    '$q',
    '$window',
    '$document',
    'Constants',
    'ajaxServiceFactory',
    'storageService',
    'signonService',
    '$ocLazyLoad',
    'routerService',
    'commonService',
    '$filter'
  ];
  function mainController(
    $rootScope,
    $scope,
    $log,
    $translate,
    $locale,
    $location,
    $q,
    $window,
    $document,
    Constants,
    ajaxServiceFactory,
    storageService,
    signonService,
    $ocLazyLoad,
    routerService,
    commonService,
    $filter
  ) {
    var hadBindKeyDown,
      watcher,
      ctrl = this,
      log = $scope.loggerFactory.getLogger('mainController');
    $rootScope.hasBackdrop = function() {
      var backdrop = $document[0].querySelector('.modal-backdrop');
      if (backdrop && !hadBindKeyDown) {
        $document.bind('keydown', function(event) {
          if (event.keyCode == 9) {
            backdrop.focus();
            event.preventDefault();
            event.stopPropagation();
          }
        });
        hadBindKeyDown = true;
      } else if (!backdrop && hadBindKeyDown) {
        $document.unbind('keydown');
        hadBindKeyDown = false;
      }
      return backdrop ? true : false;
    };
    angular.element($window).on('resize', windowResizedCallback);
    angular.element($window).bind('scroll', windowScrolledCallback);
    $scope.$watch(verticalScrollbarExpress, verticalScrollbarChangedCallback);
    $scope.$watch(contentWatchExpress, contentWatchCallback);
    ctrl.$onInit = function() {
      // TODO : config menus
      initApplicationSetting();
      signonService.isAuthenticated().then(
        function() {
          $rootScope.user = storageService.getUserInfo();
          $rootScope.site = storageService.getSiteInfo();
          $rootScope.menus = storageService.getMenuInfo();
          $rootScope.systemInfo = storageService.getSystemInfo();
          $rootScope.updateTheme();
          $rootScope.initLocaleData();
          //$rootScope.initNotificationData();
          $ocLazyLoad
            .load(
              [
                'resources/' + $scope.app.settings.theme + '/nux/css/app.css',
                'resources/' + $scope.app.settings.theme + '/nux/css/iconfont.css',
                'resources/' + $scope.app.settings.theme + '/nux/js/router/pageRouter.js',
                'resources/' + $scope.app.settings.theme + '/nux/js/router/lookupRouter.js',
                'resources/' + $scope.app.settings.theme + '/nux/js/router/popupRouter.js',
                'resources/' + $scope.app.settings.theme + '/nux/js/router/routerConfig.js'
              ],
              {
                cache: true
              }
            )
            .then(
              function() {
                /*if ($location.state()) {
								$scope.go($location.state());
							} else if($location.url()) {
								$scope.go($location.url().substr(1).split('/').join('.'));
							} else {*/
                if ($rootScope.user && $rootScope.menus && 'EXPORTER' == $rootScope.user.companyType) {
                  var menuItems = $rootScope.menus,
                    welcomeMenuConfig;
                  for (var i = 0; i < menuItems.length; i++) {
                    var menuConfig = menuItems[i];
                    if (menuConfig && Constants.SELLER_WELCOME_MENU_DISPLAY_NAME == menuConfig.displayName) {
                      welcomeMenuConfig = menuConfig;
                      break;
                    }
                  }
                  $scope.go(Constants.SELLER_WELCOME_URL, welcomeMenuConfig);
                } else {
                  $scope.go(Constants.WELCOME_URL);
                }
                //}
              },
              function(error) {
                log.error(error);
              }
            );
        },
        function() {
          $ocLazyLoad
            .load(['resources/' + $scope.app.settings.theme + '/nux/css/app.css'], {
              cache: true
            })
            .then(
              function() {
                $rootScope.$emit(Constants.NOTIFY_REDIRECT, {
                  url: 'signon.do'
                });
              },
              function(error) {
                log.error(error);
              }
            );
        }
      );
    };
    ctrl.exit = function() {
      $rootScope.unloadCheck().then(function() {
        $rootScope.disableUnloadCheck();
        signonService.exit().then(function() {
          log.debug('had signoff');
          /*$rootScope.$emit(Constants.NOTIFY_REDIRECT, {
						url : "signon.do"
					});*/
        }, angular.noop);
      });
    };

    watcher = $rootScope.$watch(
      'app',
      function(settings) {
        storageService.saveSystemSettings(settings);
      },
      true
    );

    $rootScope.$on('$destroy', function() {
      (watcher || angular.noop)();
    });

    function initApplicationSetting() {
      var defaultApp = {
        settings: {
          theme: Constants.THEME_DEFAULT,
          logLevel: $log.logLevels['*']
        }
      };
      $rootScope.app = angular.merge(defaultApp, storageService.getSystemSettings());
    }

    $rootScope.initLocaleData = function() {
      var defer = $q.defer();
      var userLocalesAjaxService = ajaxServiceFactory.buildAjaxService({
        getUserLocales: {
          url: 'locales.do',
          method: 'post'
        }
      });
      userLocalesAjaxService.getUserLocales().then(function(response) {
        var systemInfo = storageService.getSystemInfo();
        var language = storageService.getCookie(systemInfo.LOCALE_COOKIE_NAME) || storageService.getUserInfo().locale || $translate.proposedLanguage() || $translate.resolveClientLocale() || 'en_US';
        $scope.langs = {};
        angular.forEach(response.data, function(optionItem, index) {
          $scope.langs[optionItem.value] = optionItem.display;
        });
        $scope.selectLang = $scope.langs[language] || 'English';
        $scope.language = language;
        $scope.I18N.language = $scope.langs[language] ? language : 'en_US';
        //storageService.setCookie(systemInfo.LOCALE_COOKIE_NAME, language, 30, false);
        loadCommonResource(language);
        // change page locale
        $scope.setLang = function(language, $event) {
          if ($scope.selectLang != $scope.langs[language]) {
            $scope.language = language;
            $scope.selectLang = $scope.langs[language];
            // java session
            var changeLocaleAjaxService = ajaxServiceFactory.buildAjaxService({
              changeLocale: {
                url: 'changeLocale.do',
                method: 'post'
              }
            });
            changeLocaleAjaxService.changeLocale({ locale: language }).then(function(response) {
              var stateName = $scope.$state.current.name;
              if (stateName) {
                var url = stateName.split('_');
                if (url.length > 2) {
                  url = url.slice(-2);
                  url = 'resource/' + url.join('/') + '.do';
                } else {
                  url = 'resource/common/home.do';
                }
                var loadResourceAjaxService = ajaxServiceFactory.buildAjaxService({
                  loadConfig: {
                    url: url,
                    method: 'get'
                  }
                });
                loadResourceAjaxService.loadConfig().then(function(response) {
                  var resources = response ? response.data : null;
                  //storageService.setCookie(systemInfo.LOCALE_COOKIE_NAME, language, 30, false);
                  if (resources) {
                    storageService.setItemToSession(Constants.SESSION_I18N_RESOURES, resources);
                    //storageService.setItemToSession(Constants.SESSION_I18N_VALIDATION_RESOURES, {});
                    $rootScope.$emit(Constants.NOTIFY_CHANGE_LANGUAGE, {
                      language: language
                    });
                  } else {
                    loadCommonResource(language);
                  }
                });
                userLocalesAjaxService.getUserLocales().then(function(response) {
                  angular.forEach(response.data, function(optionItem, index) {
                    $scope.langs[optionItem.value] = optionItem.display;
                  });
                  $scope.selectLang = $scope.langs[language] || 'English';
                });
              }
            });
          }
        };
        defer.resolve();
      });
      return defer.promise;
    };

    $rootScope.initNotificationData = function() {
      var defer = $q.defer();
      var notificationsAjaxService = ajaxServiceFactory.buildAjaxService({
        getNotifications: {
          url: 'deliMessage/notifications.do',
          method: 'post'
        }
      });
      notificationsAjaxService.getNotifications().then(function(response) {
        $scope.notificationWrap = {};
        $scope.notificationWrap.allNum = response.data.allNum;
        $scope.notificationWrap.notifications = response.data.msgData;
        defer.resolve();
      });
      return defer.promise;
    };
    $scope.notificationItemRedirect = function(notification) {
      $scope.go('deliMessage.view', { deliMessageId: notification.deliMessageId, deliveryFolder: 'R' });
    };
    $scope.notificationListRedirect = function() {
      $scope.go('deliMessage.list');
    };

    $rootScope.updateTheme = function() {
      var userInfo = storageService.getUserInfo();
      var theme = userInfo ? userInfo.themeName || $rootScope.app.settings.theme : $rootScope.app.settings.theme;
      $rootScope.app.settings.theme = theme;
      routerService.setTheme(theme);
      updateLogo();
    };
    function updateLogo() {
      commonService.getLogo().then(function(response) {
        $rootScope.logo = response;
      });
    }
    $rootScope.auditAndNoteButtons = [
      {
        name: 'note',
        enabled: '!disabledAuditOrNote',
        tooltip: 'label.note.create',
        type: 'button',
        btnClass: 'btn-icon',
        options: {
          icon: 'note',
          callback: {
            click: 'createNote'
          }
        },
        btnScope: $scope
      },
      {
        name: 'audit',
        enabled: '!disabledAuditOrNote',
        tooltip: 'label.audit.viewaudit',
        type: 'button',
        btnClass: 'btn-icon',
        options: {
          icon: 'audit',
          callback: {
            click: 'viewAudit'
          }
        },
        btnScope: $scope
      }
    ];

    ctrl.subCompany = $rootScope._subCompany || {};
    ctrl.filterSubCompany = function() {
      // TODO: filter by $rootScope._subCompany.subCompanyKeyWord
    };
    $rootScope.showSubCompanySelector = false;
    $rootScope._subCompany = ctrl.subCompany;
    ctrl._subCompanyChanged = function(entity, formCtrl, isInitialized) {
      if (isInitialized) {
        return;
      }
      if (ctrl.subCompany && ctrl.subCompany.companyCode && $filter('encode')($rootScope._oldCompanyCode) != $filter('encode')(ctrl.subCompany.companyCode)) {
        $rootScope._oldCompanyCode = ctrl.subCompany.companyCode;
        $scope.go('poi.dashboard.panels', ctrl.subCompany);
      }
    };
    commonService.getCompanies().then(function(response) {
      ctrl.subCompanyOption = response;
      //set default value
      if (response && response.length > 0) {
        ctrl.subCompany.defaultCompanyCode = response[0].value;
        ctrl.subCompany.companyCode = ctrl.subCompany.defaultCompanyCode;
        $rootScope._subCompany = ctrl.subCompany;
      }
      $rootScope._oldCompanyCode = ctrl.subCompany.companyCode;
      ctrl.layoutConfig = {
        subCompanyConfig: {
          name: 'subCompanyConfig',
          gridGroups: [
            {
              grids: ['subCompany']
            }
          ],
          gridConfigs: {
            subCompany: {
              name: 'subCompany',
              model: 'companyCode',
              type: 'customer-select',
              template: 'company',
              size: 12,
              options: {
                hasEmptyOption: false,
                filter: {
                  model: 'subCompanyKeyWord',
                  type: 'text',
                  options: {
                    callback: {
                      changed: 'mainCtrl.filterSubCompany'
                    }
                  },
                  placeholder: 'Filter Key Word'
                },
                callback: {
                  changed: 'mainCtrl._subCompanyChanged'
                },
                data: 'mainCtrl.subCompanyOption'
              }
            }
          }
        }
      };
    });
    function loadCommonResource(language) {
      ajaxServiceFactory
        .buildAjaxService({
          loadConfig: {
            url: 'resource/common/home.do',
            method: 'get'
          }
        })
        .loadConfig()
        .then(function(response) {
          var resources = response ? response.data : null;
          if (resources) {
            storageService.setItemToSession(Constants.SESSION_I18N_RESOURES, resources);
            //storageService.setItemToSession(Constants.SESSION_I18N_VALIDATION_RESOURES, {});
            $rootScope.$emit(Constants.NOTIFY_CHANGE_LANGUAGE, {
              language: language
            });
          }
        });
    }
    function verticalScrollbarExpress() {
      var body = $document[0].documentElement || $document[0].body;
      var appContentHeight = $document[0].querySelector('.app .app-view .app-content').offsetHeight;
      var hasVerticalScrollbar = body.clientHeight - appContentHeight < 84 + 88;
      return hasVerticalScrollbar;
    }
    function contentWatchExpress() {
      var body = $document[0].documentElement || $document[0].body;
      var appView = $document[0].querySelector('.app-view');
      return body.clientHeight < appView.offsetHeight;
    }
    function windowResizedCallback($event) {
      var body = $document[0].documentElement || $document[0].body;
      var hasVerticalScrollbar = body.clientHeight - body.offsetHeight < 0;
      adjustFooter(hasVerticalScrollbar);
      adjustFixedBottom();
    }
    function windowScrolledCallback($event) {
      adjustFixedBottom();
    }
    function contentWatchCallback(contentIsHigher, oldContentIsHigher) {
      adjustLeftMenuBar(contentIsHigher);
    }
    function verticalScrollbarChangedCallback(hasVerticalScrollbar, oldHasVerticalScrollbar) {
      adjustFooter(hasVerticalScrollbar);
    }
    function adjustLeftMenuBar(contentIsHigher) {
      if (contentIsHigher) {
        angular.element($document[0].querySelector('.app-content-header')).css({
          'border-bottom-right-radius': '4px'
        });
      } else {
        angular.element($document[0].querySelector('.app-content-header')).css({
          'border-bottom-right-radius': '0'
        });
      }
    }
    function adjustFooter(hasVerticalScrollbar) {
      if (!hasVerticalScrollbar) {
        angular.element($document[0].querySelector('.app-footer')).css({
          position: 'fixed'
        });
      } else {
        angular.element($document[0].querySelector('.app-footer')).css({
          position: 'relative'
        });
      }
    }
    function adjustFixedBottom() {
      var fixedBottom = $document[0].querySelector('.navbar-fixed-bottom');
      if (!fixedBottom) {
        return;
      }
      var footer = $document[0].querySelector('.app-footer');
      var body = $document[0].documentElement || $document[0].body;
      if (body.offsetHeight - body.clientHeight - body.scrollTop < 84) {
        angular.element(fixedBottom).css({
          marginBottom: 84 - (body.offsetHeight - body.clientHeight - body.scrollTop) + 'px'
        });
      } else if (angular.element(fixedBottom).css('marginBottom') != 0) {
        angular.element(fixedBottom).css({
          marginBottom: 0
        });
      }
    }
  }
})(angular);
